import 'package:dio/dio.dart';
import 'package:wan_android_flutter/http/interceptor/cookie_interceptor.dart';
import 'package:wan_android_flutter/http/interceptor/print_log_interceptor.dart';
import 'package:wan_android_flutter/http/interceptor/rsp_interceptor.dart';

import 'http_method.dart';

class DioInstance {
  static DioInstance? _instance;

  DioInstance._();

  static DioInstance instance() {
    return _instance ??= DioInstance._();
  }

  final Dio _dio = Dio();
  final _defaultTime = Duration(seconds: 30);

  void initDio(
      {required String baseUrl,
      String? httpMethod = HttpMethod.GET,
      Duration? connectTimeout,
      Duration? receiveTimeout,
      Duration? sendTimeout,
      ResponseType? responseType = ResponseType.json,
      String? contentType}) {
    _dio.options = BaseOptions(
      method: httpMethod,
      baseUrl: baseUrl,
      connectTimeout: connectTimeout ?? _defaultTime,
      receiveTimeout: receiveTimeout ?? _defaultTime,
      sendTimeout: sendTimeout ?? _defaultTime,
      responseType: responseType,
      contentType: contentType,
    );
    _dio.interceptors.add(CookieInterceptor());
    _dio.interceptors.add(PrintLogInterceptor());
    _dio.interceptors.add(RspInterceptor());
  }

  Future<Response> get(
      {required String path,
      Map<String, dynamic>? params,
      Options? options,
      CancelToken? cancelTaken}) async {
    return await _dio.get(path,
        queryParameters: params,
        options: options ??
            Options(
                method: HttpMethod.GET,
                receiveTimeout: _defaultTime,
                sendTimeout: _defaultTime),
        cancelToken: cancelTaken);
  }

  Future<Response> post(
      {required String path,
      Object? data,
      Map<String, dynamic>? queryParameters,
      Options? options,
      CancelToken? cancelTaken}) async {
    return await _dio.post(path,
        queryParameters: queryParameters,
        data: data,
        options: options ??
            Options(
                method: HttpMethod.GET,
                receiveTimeout: _defaultTime,
                sendTimeout: _defaultTime),
        cancelToken: cancelTaken);
  }

  void changeBaseUrl(String baseUrl){
    _dio.options.baseUrl = baseUrl;
  }
}
